<template>
  <div class="user-outer">
    <!-- 搜索版块 -->
    <div class="search_box">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input placeholder="用户名" v-model="searchUser" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button
            type="primary"
            @click="
              () => {
                searchUser = '';
                set();
              }
            "
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="list_box_but1">
      <el-button type="primary" @click="add">新增用户</el-button>
      <el-button type="primary" @click="deleteAll">批量删除</el-button>
    </div>

    <div class="list_table">
      <el-table
        ref="multipleTableRef"
        :data="data"
        @selection-change="handleSelectionChange"
        :height="tableHeight"
        stripe
        :header-cell-style="{ background: '#EEF1F6' }"
      >
        <el-table-column type="selection" />
        <el-table-column label="ID" prop="id"></el-table-column>
        <el-table-column label="用户头像" width="120">
          <template v-slot="scope">
            <img
              :src="getUrl(scope.row.avatar)"
              style="width: 88px; object-fit: cover"
            />
            <el-upload
              ref="uploadRef"
              class="upload"
              :action="getUrl('/mv/upload')"
              :data="{ type: 'avatar' }"
              :auto-upload="true"
              :show-file-list="false"
              :on-success="(response:any) => updateInfo(response, scope.row.id)"
            >
              <el-button>更新图片</el-button>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column label="用户名" prop="name"></el-table-column>
        <el-table-column label="性别">
          <template v-slot="scope">
            <div>{{ changeSex(scope.row.sex) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" prop="phone"></el-table-column>
        <el-table-column label="生日">
          <template v-slot="scope">
            <div>{{ getBirth(scope.row.birth) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="签名" prop="introduction"></el-table-column>
        <el-table-column label="地区" prop="location"></el-table-column>
        <el-table-column align="center" label="操作" width="160" v-slot="scope">
          <el-button @click="editRow(scope.row)"> 编辑 </el-button>
          <el-button type="danger" @click="deleteRow(scope.row.id)">
            删除
          </el-button>
        </el-table-column>
      </el-table>
    </div>

    <div class="list_pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, prev, pager, next"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <!--添加歌曲-->
    <!-- 删除一个数据 -->
    <Deldialog
      :delVisible="delVisible"
      @confirm="confirm"
      @cancelRow="delVisible = $event"
      @closeDialog="closeDialog"
    />
    <!-- 批量删除多个数据 -->
    <Deldialog
      :delVisible="delAllVisible"
      @confirm="confirmAll"
      @cancelRow="delAllVisible = $event"
      @closeDialog="closeAllDialog"
    />
    <!-- 新建的弹出框 -->
    <el-dialog
      :title="operate ? '新曾用户' : '修改用户'"
      v-model="operateVisible"
      :destroy-on-close="true"
      @close="clearInfo"
    >
      <el-form
        ref="updateForm"
        :model="infoForm"
        :rules="SignUpRules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item prop="name" label="用户名">
          <el-input v-model="infoForm.name" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="infoForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="sex" label="性别">
          <el-radio-group v-model="infoForm.sex">
            <el-radio :label="0">女</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="birth" label="生日">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="infoForm.birth"
            :disabled-date="disabledDate"
            style="width: 200px"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="introduction" label="签名">
          <el-input
            type="textarea"
            placeholder="签名"
            v-model="infoForm.introduction"
            style="width: 600px"
          ></el-input>
        </el-form-item>
        <el-form-item prop="location" label="地区">
          <el-select
            v-model="infoForm.location"
            placeholder="地区"
            style="width: 200px"
          >
            <el-option
              v-for="item in AREA"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="phone" label="手机">
          <el-input
            placeholder="手机"
            v-model="infoForm.phone"
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="operateVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMsg(updateForm)"
            >保存</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { getAllUser, delUser, delUsers, addUserMsg, updateUser } from "@/api";
import { getUrl } from "@/utils copy/format";
import Deldialog from "@/views/components/Deldialog.vue";
const data = ref([]);
const tableData = ref([]); // 记录歌曲，用于显示
const currentPage = ref(1);
const disabled = ref(false);
const pageSize = ref(10);
const small = ref(false);
const background = ref(true);
const idx = ref(-1); // 记录当前要删除的行
const multipleSelection = ref([]); // 记录当前要删除的列表
const multipleSelectionId = ref({}); // 记录当前要删除的列表的用户id
const delVisible = ref(false); // 显示删除框
const delAllVisible = ref(false); // 显示批量删除框
const searchUser = ref("");
const tableHeight = ref(0);
const operate = ref(1);
tableHeight.value = window.innerHeight - 205;
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now();
};
const infoForm = ref({
  name: "",
  sex: -1,
  phone: "",
  birth: null,
  introduction: "",
  location: "",
  password: "",
});
let operateId: number;
const editRow = (row: any) => {
  operate.value = 0;
  infoForm.value = row;
  operateId = row.id;
  operateVisible.value = true;
};
async function handleSearch() {
  currentPage.value = 1;
  tableData.value = data.value = await getAllUser(searchUser.value.trim());
}
async function updateInfo(response: any, id: number) {
  await updateUser({ id, avatar: response.data });
  set();
}
const clearInfo = () => {
  infoForm.value = {
    name: "",
    sex: -1,
    phone: "",
    birth: null,
    introduction: "",
    location: "",
    password: "",
  };
};
function deleteRow(id: number) {
  idx.value = id;
  delVisible.value = true;
  console.log("运行过了", delVisible);
}
async function confirmAll() {
  const success = await delUsers(multipleSelectionId.value);
  if (success) {
    set();
    ElMessage.success("批量删除用户成功");
  } else {
    ElMessage.error("删除失败");
  }
  delAllVisible.value = false;
}
function closeAllDialog() {
  delAllVisible.value = false;
}
async function confirm() {
  const success = await delUser(idx.value);
  console.log("confirm运行了");
  if (success) {
    set();
    ElMessage.success("删除成功");
  } else {
    ElMessage.error("删除失败");
  }
  delVisible.value = false;
}
function closeDialog() {
  delVisible.value = false;
}
//多选的数据
function handleSelectionChange(val: any) {
  multipleSelection.value = val;
}
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  getData();
};
const handleCurrentChange = (val: any) => {
  currentPage.value = val;
  console.log(`current page: ${val}`);
  getData();
};
//删除所有选中数据
function deleteAll() {
  multipleSelectionId.value = [];
  for (let item of multipleSelection.value) {
    multipleSelectionId.value.push(item.id);
  }
  delAllVisible.value = true;
  console.log("批量" + delAllVisible.value + multipleSelectionId.value);
}

function getData() {
  data.value = tableData.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  );
}
function changeSex(value: any) {
  if (value === 0) {
    return "女";
  } else if (value === 1) {
    return "男";
  } else if (value === 2) {
    return "保密";
  } else if (value === 3) {
    return "不明";
  } else if (value === "男" || value === "女") {
    return value;
  }
}
// 解析日期
function getBirth(cellValue: any) {
  if (cellValue == null || cellValue == "") return "";
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1;
  const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  return year + "-" + month + "-" + day;
}

async function set() {
  currentPage.value = 1;
  tableData.value = [];
  const users = await getAllUser("");
  tableData.value = users;
  getData();
}
onMounted(() => {
  set();
});
//这里是添加用户的信息
import type { FormInstance } from "element-plus";
import { updateUserMsg } from "@/api";
const updateForm = ref<FormInstance>();
const operateVisible = ref(false);
function add() {
  operateVisible.value = true;
  operate.value = 1;
}
import { ElMessage } from "element-plus";
import { AREA } from "@/utils copy/format";
function saveMsg(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let res: any;
      if (operate.value) {
        res = await addUserMsg(infoForm.value);
      } else {
        res = await updateUserMsg({ ...infoForm.value, id: operateId });
      }
      if (res) {
        ElMessage.success("操作成功");
        operateVisible.value = false;
        set();
      } else {
        ElMessage.error("出错啦，操作失败");
      }
    } else {
      ElMessage.error("表单校验失败");
    }
  });
}
const SignUpRules = {
  name: { required: true, trigger: "blur", message: "请输入用户名" },
  password: { required: true, trigger: "blur", message: "请输入密码" },
  sex: { required: true, message: "请选择性别", trigger: ["blur", "change"] },
  phone: { required: true, message: "请输入电话号码", trigger: "blur" },
  birth: {
    required: true,
    type: "date",
    message: "请选择日期",
    trigger: "change",
  },

  introduction: { required: true, message: "请输入介绍", trigger: "blur" },
  location: { required: true, message: "请输入地区", trigger: "change" },
};
</script>
<style lang="scss" scoped>
@import "@/static/css/common.scss";

svg {
  width: 14px;
  height: 14px;
  fill: #fff;
  margin-right: 4px;
}

:deep(.el-table__cell) {
  border-bottom: none !important;
}

.inner_icon {
  fill: #4d70ff;
  margin-right: 2px;
}

.inner_icon:hover {
  fill: #2d56fa;
}

.user-outer {
  padding-bottom: 10px;
}

.list_box_but1 {
  position: absolute;
  top: 18px;
  right: 30px;
}
.list_box1 {
  text-indent: 0;
  background: #fff;
  border-radius: 4px;
  overflow: auto;
}
.list_box_but,
.list_table {
  width: 98%;
  margin: 0 auto;
  margin-top: 10px;
  text-indent: 0;
}
.list_box_but a {
  color: #fff;
}
.list_pagination {
  //padding-top: 14px;
  text-indent: 0;
  > div {
    justify-content: flex-end;
    margin-right: 20px;
  }
}
</style>
